<?php

class Objects extends Onecore_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model("modules_model");
        $this->load->model("elem_test_model");
        $this->load->model("elem_ppt_model");
        $this->load->model("elem_ppt_slide_model");
        $this->load->model("objects_model");
        $this->_moduleName = utf8_encode("Modulo modulos_model");
        $this->_moduleDescription = utf8_encode("Description") . $this->_moduleName;
        $this->_modelInstance = $this->objects_model;
    }
    /*
     * permite validar si el modulo a cargar pertenece a algun grupo del usuario logueado
     */
    private function belongsToGroup($idModule){
        $groups = $this->session->userdata('groups');
        foreach ($groups as $group){
            if($this->auth_model->groupHasModule($group->groups_id,$idModule)){
                return true;
            }
        }
        return false;
    }

    public function index($id){
        $data['breadcumb'] = "Tema 1 de ejemplo ";
        $this->layout->view("/object/index",$data);
    }
 
    public function clinicalcase($id=null){
        $cfg = $this->config->item('defaultCfg');

        if(!empty($id)){
            $object = $this->objects_model->getFull($id);
            $data['object'] = $object;
        }
        
        $data['breadcumb'] = "Caso Clínico";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/clinicalcase",$data);
    }
    public function theme($id=null){
        $cfg = $this->config->item('defaultCfg');

        if(!empty($id)){
            $object = $this->objects_model->getFull($id);
            $data['object'] = $object;
        }

        $data['breadcumb'] = "Tema";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/theme",$data);
    }

    public function themes(){
        $cfg = $this->config->item('defaultCfg');
        $data['breadcumb'] = "Tema";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/themes",$data);
    }
    public function cases(){
        $cfg = $this->config->item('defaultCfg');
        $data['breadcumb'] = "Casos";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/cases",$data);
    }
    public function centers(){
        $cfg = $this->config->item('defaultCfg');
        $data['breadcumb'] = "Casos";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/centers",$data);
    }

    public function edit(){
        $cfg = (object)$this->config->item('defaultCfg');
        $success = false;
        $valid = true;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " editado en forma exitosa";
        $errorList = array();
        
        $id = $this->input->post('id');
        $name = $this->input->post('name');
        $description = $this->input->post('description');
        $content = $this->input->post('content');
        $category_id = $this->input->post('category_id');
        $type_objects_id = $this->input->post('type_objects_id');
        $parent = $this->input->post('parent');
        $featuredImage = $this->input->post('featuredImage');
        $dmodified = date('Y-m-d H:i:s');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        
        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            //si es un objeto file
            if($type_objects_id == $cfg->type_object_file){
                if(empty($parent)){
                    $errorList[] = "El recurso debe estar asociado a un Tema mediante parametro [parent]";
                    $valid = false;
                }
                if(empty($content)){
                    $errorList[] = "El recurso debe poseer en [content] la ruta del archivo asociado";
                    $valid = false;
                }
                if(empty($category_id)){
                    $errorList[] = "El recurso debe poseer una categoria asociada mediante [category_id]";
                    $valid = false;
                }
            }
            if($valid){

                //$description = str_replace("'", "", $description);
                //$name = str_replace("'", "", $name);

                $data = array(
                    "id" => array(
                        'id'=>$id
                    ),
                    "data" => array(
                        'umodified'=>$userEmail,
                        'users_id'=>$uid,
                        "dmodified"=>$dmodified,
                        'name'=>$name,
                        'description' => $description,
                        'content' => $content,
                        'parent' => $parent,
                        'category_id' => $category_id,
                        "type_objects_id" => $type_objects_id,
                        'featuredImage'=>$featuredImage
                    )
                );
                
                if ($this->_modelInstance->save($data, true)) {
                    $success = true;
                } else {
                    $mensaje = "La Diapositiva no pudo ser creada. Verifique los siguientes errores.";
                    $errorList = array("Error" => $this->_modelInstance->getError());
                }
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "data"=>array(
                "dmodified"=>$dmodified,
                "umodified"=>$uid,
            ),
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    public function add(){
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " creado en forma exitosa";
        $errorList = array();
        
        $name = $this->input->post('name');
        $description = $this->input->post('description');
        $content = $this->input->post('content');
        $category_id = $this->input->post('category_id');
        $type_objects_id = $this->input->post('type_objects_id');
        $parent = $this->input->post('parent');
        $featuredImage = $this->input->post('featuredImage');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->_modelInstance->getValidations());
        $_id = 0;
        $_object = null;

        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            //si es un objeto file
            if($type_objects_id == $cfg->type_object_file){
                if(empty($parent)){
                    $errorList[] = "El recurso debe estar asociado a un Tema mediante parametro [parent]";
                    $valid = false;
                }
                if(empty($content)){
                    $errorList[] = "El recurso debe poseer en [content] la ruta del archivo asociado";
                    $valid = false;
                }
                if(empty($category_id)){
                    $errorList[] = "El recurso debe poseer una categoria asociada mediante [category_id]";
                    $valid = false;
                }
            }
            if($valid){
                $description = str_replace("'", "", $description);
                $name = str_replace("'", "", $name);
                $data = array(
                    "id" => "",
                    "data" => array(
                        'ucreated'=>$userEmail,
                        'users_id'=>$uid,
                        'name'=>$name,
                        'description' => $description,
                        'content' => $content,
                        'parent' => $parent,
                        'category_id' => $category_id,
                        "type_objects_id" => $type_objects_id,
                        'featuredImage'=>$featuredImage
                    )
                );
                
                if ($this->_modelInstance->save($data, false)) {
                    $_object = $this->_modelInstance->getFull($this->_modelInstance->getLastInsertedId());
                    $success = true;
                } else {
                    $mensaje = "El objeto no pudo ser creado. Verifique los siguientes errores.";
                    $errorList = array("Error" => $this->_modelInstance->getError());
                }
            }

            
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "data"=>array(
                "object"=>$_object,
                "id"=>$_id,
                "ucreated"=>$uid,
            ),
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    //relaciona objeto con otro
    public function relationate(){
        $this->load->model("objects_objects_model");
        $cfg = (object)$this->config->item('defaultCfg');
        $valid = true;
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = $itemName . " relacionado en forma exitosa";
        $errorList = array();
        
        $o1_id = $this->input->post('o1_id');
        $o2_id = $this->input->post('o2_id');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        $this->form_validation->set_rules($this->objects_objects_model->getValidations());
        
        if ($this->form_validation->run() == FALSE) {
            $mensaje = "Campos inválidos";
            $errorList = $this->form_validation->_error_array;
        } else {
            $data = array(
                "id" => "",
                "data" => array(
                    'ucreated'=>$userEmail,
                    'o1_id'=>$o1_id,
                    'o2_id' => $o2_id
                )
            );
            if ($this->objects_objects_model->save($data, false)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser relacionado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");   
    }
    //elimina relacion objeto de otro
    public function delRelation(){
        $this->load->model("objects_objects_model");
        $success = false;
        $itemName = $this->objects_objects_model->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $id = $this->input->post('id');
        $o2_id = $this->input->post('o2_id');
        $object = $this->_modelInstance->getByid($id);
      
        
        if(is_array($object)) $object = $object[0];
        
        if(!empty($object)){
            $data = array(
                "o1_id"=>$id,
                "o2_id"=>$o2_id
            );
            
            if($this->objects_objects_model->del($data)){
                $mensaje = $itemName . " elimnado en forma exitosa";
                $success = true;
            }else{
                $mensaje = "La " . $itemName . " no pudo ser eliminada. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->objects_objects_model->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
    //obtiene lista de objetos relacionados a otro
    public function getRelatedObjects(){
        $this->load->model("objects_objects_model");
        $cfg = (object)$this->config->item('defaultCfg');
        $id = $this->input->get('id');
           
        $data = $this->objects_objects_model->getObjectsById($id);
        $res = array(
            "success" => true,
            "results" => $data['results'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function get(){
        $id = $this->input->post('id');
        $object = $this->objects_model->getFull($id);

        //echo json_encode($object);exit;

        $res = array(
            "success" => true,
            "data" => $object
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function loadResourceFiles() {
        $cfg = $this->config->item('defaultCfg');

        $conditions = new stdClass();
        $conditions->start = $this->input->get('start');
        $conditions->limit = $this->input->get('limit');
        $conditions->parent = $this->input->get('parent');

        if (!$this->input->get('sort')) {
            $conditions->order = 'id';
            $conditions->direction = 'DESC';
        } else {
            $orden = $this->input->get('sort');
            $sort = json_decode($orden);
            $conditions->order = $sort[0]->property;
            $conditions->direction = $sort[0]->direction;
        }

        $conditions->type_objects_id = $cfg['type_object_file'];
        $conditions->parent = $this->input->get('parent');
        

        $data = $this->_modelInstance->loadResourceFiles($conditions);
        $res = array(
            "success" => true,
            "results" => $data['results'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }
    public function loadList() {
        $uid = $this->session->userdata('id_usuario');
        $groups_id = $this->session->userdata('groups_id');
        $userEmail = $this->session->userdata('uid');

        $cfg = $this->config->item('defaultCfg');

        $options = new stdClass();
        $options->start = $this->input->get('start');
        $options->limit = $this->input->get('limit');

        /* estas variables son usadas por la visat de temas del aluimno */
        $options->includeHit = $this->input->get('includeHit');
        $options->includeRelatedObjects = $this->input->get('includeRelatedObjects');
        $options->includeConfig = $this->input->get('includeConfig');
        $options->hitStatus = $this->input->get('hitStatus');
        $options->startExec = $this->input->get('startExec');
        $options->endExec = $this->input->get('endExec');
        $options->users_id = $uid;
        $options->groups_id = $groups_id;

        //---------------------------------------

        $options->conditions = new stdClass();


        $type_objects_id = "o.type_objects_id";
        $objectName = "o.name";
        $objectDescription = "o.description";
        $objectUCreated = "o.ucreated";
        $objectUModified = "o.umodified";
        $objectStatus = "o.status";

        $options->conditions->category_id = $this->input->get('category_id');
        $options->conditions->$type_objects_id = $this->input->get('type_objects_id');
        $options->conditions->$objectStatus = $this->input->get('status');

        $options->conditions->$objectName = $this->input->get('name');
        $options->conditions->$objectDescription = $this->input->get('description');
        $options->conditions->$objectUCreated = $this->input->get('ucreated');
        $options->conditions->$objectUModified = $this->input->get('umodified');

        $options->conditions->from = $this->input->get('fromDcreated');
        $options->conditions->to = $this->input->get('toDcreated');
        $options->conditions->deleted = $this->input->get('deleted');

        if (!$this->input->get('sort')) {
            $options->orderField = 'id';
            $options->orderDirection = 'DESC';
        } else {
            $orden = $this->input->get('sort');
            $sort = json_decode($orden);
            $options->orderField = $sort[0]->property;
            $options->orderDirection = $sort[0]->direction;
        }

        //$data = $this->_modelInstance->listEntities($options);
        $data = $this->_modelInstance->loadListCrud($options);

        $res = array(
            "success" => true,
            "results" => $data['results'],
            "rows" => $data['items']
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function loadByModule(){
        $this->load->model("modules_model");
        $this->load->model("objects_model");
        $this->load->model("objects_objects_model");
        $this->load->model("modules_objects_model");
        $this->load->model("users_exec_model");
        $this->load->model("users_model");
        $this->load->model("groups_model");

        

        $cfg = (object)$this->config->item('defaultCfg');

        $groups_id = $this->session->userdata('groups_id');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');

        $category_id = $this->input->get('category_id');
        $type_objects_id = $this->input->get('type_objects_id');
        $exeStatus = $this->input->get('hitStatus');

        $objectName = $this->input->get('name');
        $objectDescription = $this->input->get('description');
        $objectUCreated = $this->input->get('ucreated');
        $objectUModified = $this->input->get('umodified');

        $startExec = $this->input->get('startExec');
        $endExec = $this->input->get('endExec');
        $deleted = $this->input->get('deleted');

        $query = new stdClass();
        $query->conditions = new stdClass();
        $query->conditions->type_objects_id = $type_objects_id;
        $query->conditions->groups_id = $groups_id;
        $module = $this->modules_model->listEntities($query);
        $module = $module["items"][0];

        //obtenemos todos los objeto asociados al grupo y el modulo temas
        $options = new stdClass();
        $options->type_objects_id = $type_objects_id;
        $options->modules_id = $module->id;
        $options->category_id = $category_id;
        $options->autor = $objectUCreated;
        $options->modificator = $objectUModified;
        $options->name = $objectName;
        $options->description = $objectDescription;

        $objects = $this->groups_model->getRegisteredObjects($groups_id, $options);

        $objects = $objects["items"];

        //print_r($objects);exit;

        $filter = array();

        //por cada tema obtenemos childs del tema
        for ($i=0; $i < count($objects); $i++) { 
            //obtedos childs (notas de derviascion, imagenes, etc)
            $relateds = $this->objects_model->getByparent($objects[$i]->id);
            $objects[$i]->relatedObjects = array();
            //eliminamos si posee una nota
            for ($j=0; $j < count($relateds); $j++) { 
                if($relateds[$j]->type_objects_id != $cfg->type_object_note){
                    //si es nota de derivacion lo asignamos a objeto principal
                    if($relateds[$j]->category_id == $cfg->category_referralnote){
                        $objects[$i]->referralnote = $relateds[$j];
                    }
                    $objects[$i]->relatedObjects[] = $relateds[$j];
                }
            }
            //por cada objeto consultamos si posee historial de ejecucion asociada a la ultima version del objeto
            $conditions = new stdClass();
            $conditions->users_id = $uid;
            $conditions->objects_id = $objects[$i]->id;
            $conditions->type_objects_id = $type_objects_id;
            $conditions->objectversion = $objects[$i]->version;

            $objects[$i]->hit = $this->users_exec_model->lastHit($conditions);
            
            //obtenemos el usuario que creo objeto
            $user = $this->users_model->getByid($objects[$i]->users_id);
            if(!empty($user[0])){
                $objects[$i]->user = $user[0];
            }
            $objects[$i]->modules_id = $module->id;
            //si filtra por status ejecucion
            if(!empty($exeStatus)){
                //aqui pasamos de largo todos aqullols que poseen hit
                if($exeStatus == "NONE"){
                    if(!empty($objects[$i]->hit) && $objects[$i]->hit!=null){
                        continue;
                    }
                }    
                else{
                    if(!empty($objects[$i]->hit) && $objects[$i]->hit!=null){
                        if($objects[$i]->hit->status != $exeStatus){
                            continue;
                        }
                    }
                    else{
                        log_message("error","pasamos de largo");
                        continue;
                    }
                }
            }
            if(!empty($startExec)){
                if(strtotime($objects[$i]->dstart) < strtotime($startExec)){
                    continue;
                }
            }
            //si filtra por fecha cierrre
            if(!empty($endExec) ){
                if(strtotime($objects[$i]->dend) > strtotime($endExec)){
                    continue;
                }
            }
            //si filtra por fecha cierrre
            if(!empty($endExec) && !empty($startExec)){
                if(strtotime($objects[$i]->dstart) < strtotime($startExec) &&
                    strtotime($objects[$i]->dend) > strtotime($endExec)){
                    log_message("error","nos saltamos estre");
                    continue;
                }
            }
            $filter[] = $objects[$i];
        }

        $res = array(
            "success" => true,
            "results" => count($filter),
            "rows" => $filter
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function del(){
        $success = false;
        $itemName = $this->_modelInstance->getItemName();
        $mensaje = "Error inesperado";
        $errorList = array();
        
        $id = $this->input->post('id');
        $object = $this->_modelInstance->getByid($id);
      
        
        if(is_array($object)) $object = $object[0];
        
        if(!empty($object)){
            $data = array(
                "id" => array(
                    'id'=>$id
                ),
                "data" => array(
                    'deleted'=>1
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El objeto no puedo ser eliminado. Verifique los siguientes errores.";
                $errorList = array("Error" => $this->_modelInstance->getError());
            }
        }
        $data = array(
            'success' => $success,
            "msg" => $mensaje,
            "errors" => $errorList,
        );
        $this->layout->printLike(json_encode($data), "json");
    }
/*
    public function get4Exec_20140222(){
        $this->load->library('utils');
        $cfg = $this->utils->getConfig();

        $this->load->model("users_exec_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("role_group_model");

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        $object_id = $this->input->post('id');
        $module_id = $this->input->post('module_id');

        $configQuestions = array();

        //parametros validos
        if(empty($object_id) || empty($module_id)){
            $res = array(
                "success" => false,
                "message" => "Parametros invalidos"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //existe relacion entre modulo objeto
        $moduleObject = $this->modules_objects_model->get($module_id,$object_id);
        if(empty($moduleObject[0])){
            $res = array(
                "success" => false,
                "message" => "Objeto no esta relacionado al modulo"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        $moduleObject = $moduleObject[0];
        $moduleObject->config = str_replace('&quot;','"',$moduleObject->config);

        $object = $this->objects_model->getFull($object_id);
        //objeto existe
        if($object==null){
            $res = array(
                "success" => false,
                "message" => "Objeto $object_id no existe"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        
        //validamos si el objeto aun puede ejecutarse segun config de inicio y termino
        $moduleObject->config = json_decode($moduleObject->config);
        $tstart = strtotime($moduleObject->config->start);
        $dstart = $moduleObject->config->start;
        $dend = $moduleObject->config->start;
        $tend = strtotime($moduleObject->config->end);
        $now = strtotime(date("Y-m-d H:i:s"));

        //si aun no comienza
        if($tstart >= $now){
            $res = array(
                "success" => false,
                "message" => "El objeto Tema solo puede ejecutarse a partir de $dstart"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //si ya finalizo
        if($now >= $tend){
            $res = array(
                "success" => false,
                "message" => "El objeto Tema solo puede ser ejecutado hasta el $dend"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
                
        //validamos si el usuario esta en algun grupo que posee el tema asociado mediante un modulo
        //obtenemos modulo
        $module = $this->modules_model->getByid($moduleObject->modules_id);
        if(empty($module[0])){
            $res = array(
                "success" => false,
                "message" => "Modulo no existe."
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        $module = $module[0];
        $conditions = new stdClass();
        $conditions->users_id = $uid;
        $conditions->groups_id = $module->groups_id;
        $rolgroup = $this->role_group_model->get($conditions);

        //tiene el usuario asociado el objeto?
        if(empty($rolgroup[0])){
            $res = array(
                "success" => false,
                "message" => "Usuario sin permisos de acceso al objeto."
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        //el objeto esta DISABLED?
        if($object->status == $cfg->object_disabled){
            $res = array(
                "success" => false,
                "message" => "El objeto se encuentra deshabilitado por su creador"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //esta en desarrollo?
        if($object->status == $cfg->object_develop){
            $res = array(
                "success" => false,
                "message" => "El objeto se encuentra en desarrollo"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        //validamos si es necesario asignar la prueba segun estado de su ejecucion para el caso de que sea TEMA
        if(!empty($object->test)){



            $conditions = new stdClass();
            $conditions->users_id = $uid;
            $conditions->objects_id = $object->test->id;
            $conditions->type_objects_id = $object->test->type_objects_id;
            $conditions->objectversion = $object->version;

            $lastHit = $this->users_exec_model->lastHit($conditions);
            if($lastHit!=null){
                //si el usuario ya aprobo el test, eliminamos el objeto
                if($lastHit->status == $cfg->object_user_approved){
                    unset($object->test);
                }
            }
            //si la prueba no se ha eliminado del objeto registramos hit
            if(!empty($object->test)){
            //configuramos prueba si la tuviera
                if(!empty($moduleObject->config->test)){
                    $testCfg = $moduleObject->config->test;
                    //si es random, debemos seleccionar una pregunta al azar y desordenar sus respuestas
                    if($testCfg->random){
                        shuffle($object->test->questions);
                        shuffle($object->test->questions[0]->answers);

                        for($i=0;$i<$testCfg->nQuestions; $i++){
                            $configQuestions[] = $object->test->questions[$i]->id;
                        }
                    }
                    else{//si no es random, revisamos si ha seleccionado preguntas que utilizar en especifico
                        if(!empty($testCfg->selectedQuestions) && is_array($testCfg->selectedQuestions)){
                            $auxQ = array();
                            for($i=0;$i<count($object->test->questions); $i++){
                                if(in_array($object->test->questions[$i]->id, $testCfg->selectedQuestions)){
                                    $auxQ[] = $object->test->questions[$i];
                                }
                            }
                            //revolvemos de todas formas
                            shuffle($auxQ);
                            shuffle($auxQ[0]->answers);
                            $object->test->questions = $auxQ;

                            foreach($object->test->questions as $q){
                                $configQuestions[] = $q->id;
                            }

                        }
                        else{
                            $auxQ = array();
                            for($i=0;$i<$testCfg->nQuestions; $i++){
                                $auxQ[] = $object->test->questions[$i];
                                $configQuestions[] = $object->test->questions[$i]->id;
                            }
                        }
                    }
                    $object->test->questions = array($object->test->questions[0]);
                }
                else{
                    $res = array(
                        "success" => false,
                        "message" => "No existe configuracion de TEST en objeto $object->id, modulo $moduleObject->module_id"
                    );
                    $this->layout->printLike(json_encode($res), "json");
                    return;
                }
                //cada vez que se ejecuta un tema la prueba comienza de nuevo si existiesa
                //registramos hit de prueba con configuracion de preguntas a mostrar
                $hit = new stdClass();
                $hit->users_id = $uid;
                $hit->objects_id = $object->test->id;
                $hit->type_objects_id = $object->test->type_objects_id;
                $hit->objectversion = $object->version;
                $hit->status = "EXEC";
                $hit->execdetail = json_encode(array("questions"=>$configQuestions));

                //guardamos hit de prueba
                if(!$this->users_exec_model->hit($hit)){
                    $error = $this->users_exec_model->getError();
                    log_message("error","(executeTheme) No se pudo registrar hit users_id=[$uid], 
                                                        object_id=[$object_id], version=[$object->version],
                                                        type_objects_id=[$object->type_objects_id]. 
                                                        Detalle=[$error]");
                }
            }
        }

        //ultima ejecucion si la posee
        $options = new stdClass();
        $options->objects_id = $object->id;
        $options->users_id = $uid;
        $options->type_objects_id = $object->type_objects_id;
        $options->objectversion = $object->version;
        $lastHit = $this->users_exec_model->lastHit($options);
        if(!empty($lastHit)){
            //actualizamos HIT!
            $hit = new stdClass();
            $hit->id = $lastHit->id;
            $hit->dmodified = date('Y-m-d H:i:s');
            //$hit->objectversion = $cfg->object_user_exec;
            //marcamos hit ejecucion tema
            if(!$this->users_exec_model->updateHit($hit)){
                $error = $this->users_exec_model->getError();
                log_message("error","(executeTheme) No se pudo registrar hit users_id=[$uid], 
                                                    object_id=[$object_id], version=[$object->version],
                                                    type_objects_id=[$object->type_objects_id]. 
                                                    Detalle=[$error]");
            }
            $object->hit = $lastHit;
        }
        else{
            //registramos HIT!
            $hit = new stdClass();
            $hit->users_id = $uid;
            $hit->objects_id = $object->id;
            $hit->type_objects_id = $object->type_objects_id;
            $hit->objectversion = $object->version;
            $hit->status = $cfg->object_user_init;

            //marcamos hit ejecucion tema
            if(!$this->users_exec_model->hit($hit)){
                $error = $this->users_exec_model->getError();
                log_message("error","(executeTheme) No se pudo registrar hit users_id=[$uid], 
                                                    object_id=[$object_id], version=[$object->version],
                                                    type_objects_id=[$object->type_objects_id]. 
                                                    Detalle=[$error]");
            }
            $object->hit = $hit;
        }

        //buscamos si tiene notas
        $query = new stdClass();
        $query->conditions = new stdClass();
        $query->conditions->parent = $object->id;
        $query->conditions->users_id = $uid;
        $query->conditions->type_objects_id = $cfg->type_object_note;
        $notes = $this->_modelInstance->listEntities($query);
        if(count($notes['items'])>0){
            $object->note  = $notes['items'][0];
        }

        $res = array(
            "success" => true,
            "data" => $object
        );
        $this->layout->printLike(json_encode($res), "json");
    }
*/
    public function get4Exec(){
        $this->load->library('utils');
        $cfg = $this->utils->getConfig();

        $this->load->model("users_exec_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("role_group_model");

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        $object_id = $this->input->post('id');
        $module_id = $this->input->post('module_id');

        $configQuestions = array();

        //parametros validos
        if(empty($object_id) || empty($module_id)){
            $res = array(
                "success" => false,
                "message" => "Parametros invalidos"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //existe relacion entre modulo objeto
        $moduleObject = $this->modules_objects_model->get($module_id,$object_id);
        if(empty($moduleObject[0])){
            $res = array(
                "success" => false,
                "message" => "Objeto no esta relacionado al modulo"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        $moduleObject = $moduleObject[0];
        $moduleObject->config = str_replace('&quot;','"',$moduleObject->config);

        $object = $this->objects_model->getFull($object_id);
        //objeto existe
        if($object==null){
            $res = array(
                "success" => false,
                "message" => "Objeto $object_id no existe"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        
        //validamos si el objeto aun puede ejecutarse segun config de inicio y termino
        $moduleObject->config = json_decode($moduleObject->config);
        $tstart = strtotime($moduleObject->config->start);
        $dstart = $moduleObject->config->start;
        $dend = $moduleObject->config->start;
        $tend = strtotime($moduleObject->config->end);
        $now = strtotime(date("Y-m-d H:i:s"));

        //si aun no comienza
        if($tstart >= $now){
            $res = array(
                "success" => false,
                "message" => "El objeto Tema solo puede ejecutarse a partir de $dstart"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //si ya finalizo
        if($now >= $tend){
            $res = array(
                "success" => false,
                "message" => "El objeto Tema solo puede ser ejecutado hasta el $dend"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
                
        //validamos si el usuario esta en algun grupo que posee el tema asociado mediante un modulo
        //obtenemos modulo
        $module = $this->modules_model->getByid($moduleObject->modules_id);
        if(empty($module[0])){
            $res = array(
                "success" => false,
                "message" => "Modulo no existe."
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        $module = $module[0];
        $conditions = new stdClass();
        $conditions->users_id = $uid;
        $conditions->groups_id = $module->groups_id;
        $rolgroup = $this->role_group_model->get($conditions);

        //tiene el usuario asociado el objeto?
        if(empty($rolgroup[0])){
            $res = array(
                "success" => false,
                "message" => "Usuario sin permisos de acceso al objeto."
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        //el objeto esta DISABLED?
        if($object->status == $cfg->object_disabled){
            $res = array(
                "success" => false,
                "message" => "El objeto se encuentra deshabilitado por su creador"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }
        //esta en desarrollo?
        if($object->status == $cfg->object_develop){
            $res = array(
                "success" => false,
                "message" => "El objeto se encuentra en desarrollo"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        //validamos si es necesario asignar la prueba segun estado de su ejecucion 
        if(!empty($object->test)){
            //solo aplica para el caso de que sea TEMA
            if($object->type_objects_id == $cfg->type_object_theme){
                $conditions = new stdClass();
                $conditions->users_id = $uid;
                $conditions->objects_id = $object->test->id;
                $conditions->type_objects_id = $object->test->type_objects_id;
                $conditions->objectversion = $object->version;

                $lastHit = $this->users_exec_model->lastHit($conditions);
                if($lastHit!=null){
                    //si el usuario ya aprobo el test, eliminamos el objeto
                    if($lastHit->status == $cfg->object_user_approved){
                        unset($object->test);
                    }
                }
            }

            
            //si la prueba no se ha eliminado del objeto registramos hit de configuracion
            if(!empty($object->test)){
                //configuramos prueba si la tuviera
                if(!empty($moduleObject->config->test)){
                    $testCfg = $moduleObject->config->test;
                    $selecteds = array();
                    //estas config solo aplican para tema, en caso clinico se consideran todas las preguntas
                    //porque son todas de seleccion multiple    
                    if($object->type_objects_id == $cfg->type_object_theme){
                        //si es tema siempre randomizamos preguntas y respuestas
                        shuffle($object->test->questions);
                        shuffle($object->test->questions[0]->answers);

                        for($i=0;$i<$testCfg->nQuestions; $i++){
                            $selecteds[] = $object->test->questions[$i];
                            $configQuestions[] = $object->test->questions[$i]->id;
                        }
                        //$object->test->questions = array($object->test->questions[0]);
                    }
                    else{
                        //si es caso las preguntas configuradas son todas en el orden que fueron creadas
                        for($i=0;$i<count($object->test->questions); $i++){
                            $configQuestions[] = $object->test->questions[$i]->id;
                            $selecteds[] = $object->test->questions[$i];
                        }
                        
                    }
                    $object->test->questions = array($selecteds[0]);
                }
                else{
                    $res = array(
                        "success" => false,
                        "message" => "No existe configuracion de TEST en objeto $object->id, modulo $moduleObject->module_id"
                    );
                    $this->layout->printLike(json_encode($res), "json");
                    return;
                }
                //cada vez que se ejecuta un tema la prueba comienza de nuevo si existiesa
                //registramos hit de prueba con configuracion de preguntas a mostrar
                $hit = new stdClass();
                $hit->users_id = $uid;
                $hit->objects_id = $object->test->id;
                $hit->type_objects_id = $cfg->type_object_test;
                $hit->objectversion = $object->version;
                $hit->status = "EXEC";
                $hit->execdetail = json_encode(array("questions"=>$configQuestions));

                //guardamos hit de prueba
                if(!$this->users_exec_model->hit($hit)){
                    $error = $this->users_exec_model->getError();
                    log_message("error","(executeTheme) No se pudo registrar hit users_id=[$uid], 
                                                        object_id=[$object_id], version=[$object->version],
                                                        type_objects_id=[$object->type_objects_id]. 
                                                        Detalle=[$error]");
                }
            }
        }

        //ultima ejecucion si la posee
        $options = new stdClass();
        $options->objects_id = $object->id;
        $options->users_id = $uid;
        $options->type_objects_id = $object->type_objects_id;
        $options->objectversion = $object->version;
        $lastHit = $this->users_exec_model->lastHit($options);
        if(!empty($lastHit)){
            //actualizamos HIT!
            $hit = new stdClass();
            $hit->id = $lastHit->id;
            $hit->dmodified = date('Y-m-d H:i:s');
            //$hit->objectversion = $cfg->object_user_exec;
            //marcamos hit ejecucion tema
            if(!$this->users_exec_model->updateHit($hit)){
                $error = $this->users_exec_model->getError();
                log_message("error","(executeTheme) No se pudo actualizar hit users_id=[$uid], 
                                                    object_id=[$object_id], version=[$object->version],
                                                    type_objects_id=[$object->type_objects_id]. 
                                                    Detalle=[$error]");
            }
            $object->hit = $lastHit;
        }
        else{
            //registramos HIT!
            $hit = new stdClass();
            $hit->users_id = $uid;
            $hit->objects_id = $object->id;
            $hit->type_objects_id = $object->type_objects_id;
            $hit->objectversion = $object->version;
            $hit->status = $cfg->object_user_init;

            //marcamos hit ejecucion tema
            if(!$this->users_exec_model->hit($hit)){
                $error = $this->users_exec_model->getError();
                log_message("error","(executeTheme) No se pudo registrar hit users_id=[$uid], 
                                                    object_id=[$object_id], version=[$object->version],
                                                    type_objects_id=[$object->type_objects_id]. 
                                                    Detalle=[$error]");
            }
            $object->hit = $hit;
        }

        //buscamos si tiene notas
        $query = new stdClass();
        $query->conditions = new stdClass();
        $query->conditions->parent = $object->id;
        $query->conditions->users_id = $uid;
        $query->conditions->type_objects_id = $cfg->type_object_note;
        $notes = $this->_modelInstance->listEntities($query);
        if(count($notes['items'])>0){
            $object->note  = $notes['items'][0];
        }

        $res = array(
            "success" => true,
            "data" => $object
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function executeTheme($object_id=null,$module_id=null){
        $this->load->model("users_exec_model");
        $this->load->library('utils');

        $cfg = $this->utils->getConfig();

        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("role_group_model");

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        //parametros validos
        if(empty($object_id) || empty($module_id)){
            $error = new stdClass();
            $error->title = "Parametros inválidos";
            $error->message = "";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/400",$data);
            return;
        }
        //existe relacion entre modulo objeto
        $moduleObject = $this->modules_objects_model->get($module_id,$object_id);
        if(empty($moduleObject[0])){
            $error = new stdClass();
            $error->title = "El Tema [$object_id] no esta relacionado al módulo [$module_id]";
            $error->message = "Datos inválidos";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }

        $moduleObject = $moduleObject[0];
        $moduleObject->config = str_replace('&quot;','"',$moduleObject->config);
        $object = $this->objects_model->getFull($object_id);
        //objeto existe
        if($object==null){
            $error = new stdClass();
            $error->title = "El Tema [$object_id] no existe en el sistema";
            $error->message = "Datos inválidos";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/404",$data);
            return;
        }
        
        $object->_moduleId = $module_id;
        //print_r($moduleObject);exit;

        //print_r($moduleObject);exit;
        //validamos si el objeto aun puede ejecutarse segun config de inicio y termino
        $moduleObject->config = json_decode($moduleObject->config);
        $tstart = strtotime($moduleObject->config->start);
        $dstart = $moduleObject->config->start;
        $dend = $moduleObject->config->start;
        $tend = strtotime($moduleObject->config->end);
        $now = strtotime(date("Y-m-d H:i:s"));

        //si aun no comienza 403
        if($tstart >= $now){
            $error = new stdClass();
            $error->title = "El Tema [$object->name] solo puede ser ejecutado a partir de $dstart";
            $error->message = "Fecha configurada por el administrador al momento de inscribir.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //si ya finalizo 403
        if($now >= $tend){
            $error = new stdClass();
            $error->title = "El Tema [$object->name] solo puede ser ejecutado hasta el $dend";
            $error->message = "Fecha configurada por el administrador al momento de inscribir.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
                
        //validamos si el usuario esta en algun grupo que posee el tema asociado mediante un modulo
        //obtenemos modulo
        $module = $this->modules_model->getByid($moduleObject->modules_id);
        if(empty($module[0])){
            $error = new stdClass();
            $error->title = "Modulo [$moduleObject->modules_id] no existe";
            $error->message = "Tema mal configurado con modulo y grupo.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/404",$data);
            return;
        }

        $module = $module[0];
        $conditions = new stdClass();
        $conditions->users_id = $uid;
        $conditions->groups_id = $module->groups_id;
        $rolgroup = $this->role_group_model->get($conditions);

        //tiene el usuario asociado el objeto? 403
        if(empty($rolgroup[0])){
            $error = new stdClass();
            $error->title = "Usuario [$userEmail] sin permisos de acceso al Tema $object->name";
            $error->message = "El Tema no esta relacionado con los temas inscritos al usuario.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //el objeto esta DISABLED?
        if($object->status == $cfg->object_disabled){
            $error = new stdClass();
            $error->title = "El Tema se encuentra deshabilitado por su creador";
            $error->message = "";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //esta en desarrollo? 403
        if($object->status == $cfg->object_develop){
            $error = new stdClass();
            $error->title = "El Tema se encuentra en desarrollo";
            $error->message = "El creador del tema se encuentra efectuando cambios.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }

        $data['object'] = $object;
        $data['breadcumb'] = "Tema";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/theme_exec",$data);
    }
    public function executeCase($object_id=null,$module_id=null){
        $this->load->model("users_exec_model");
        $this->load->library('utils');

        $cfg = $this->utils->getConfig();

        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("role_group_model");
        $this->load->model("objects_objects_model");

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        
        //parametros validos 400
        if(empty($object_id) || empty($module_id)){
            $error = new stdClass();
            $error->title = "Parametros inválidos";
            $error->message = "";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/400",$data);
            return;
        }
        //existe relacion entre modulo objeto 404
        $moduleObject = $this->modules_objects_model->get($module_id,$object_id);
        if(empty($moduleObject[0])){
            $error = new stdClass();
            $error->title = "El Caso [$object_id] no esta relacionado al módulo [$module_id]";
            $error->message = "Datos inválidos";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/404",$data);
            return;
        }

        $moduleObject = $moduleObject[0];
        $moduleObject->config = str_replace('&quot;','"',$moduleObject->config);
        $object = $this->objects_model->getFull($object_id);
        //objeto no existe 404
        if($object==null){
            $error = new stdClass();
            $error->title = "El Caso [$object_id] no existe en el sistema";
            $error->message = "Datos inválidos";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/404",$data);
            return;
        }
        
        $object->_moduleId = $module_id;
        //validamos si el objeto aun puede ejecutarse segun config de inicio y termino
        $moduleObject->config = json_decode($moduleObject->config);
        if(empty($moduleObject->config)){
            $error = new stdClass();
            $error->title = "El Caso [$object_id] esta mal configurado en relación al modulo [$module_id]";
            $error->message = "El autor del caso debe configurar la prueba al momento de inscribir Caso en Grupo.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }


        $tstart = strtotime($moduleObject->config->start);
        $dstart = $moduleObject->config->start;
        $dend = $moduleObject->config->start;
        $tend = strtotime($moduleObject->config->end);
        $now = strtotime(date("Y-m-d H:i:s"));

        //si aun no comienza 403
        if($tstart >= $now){
            $error = new stdClass();
            $error->title = "El Caso [$object->name] solo puede ser ejecutado a partir de $dstart";
            $error->message = "Fecha configurada por el administrador al momento de inscribir el Caso.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //si ya finalizo 403
        if($now >= $tend){
            $error = new stdClass();
            $error->title = "El Caso [$object->name] solo puede ser ejecutado hasta el $dend";
            $error->message = "Fecha configurada por el administrador al momento de inscribir el Caso.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
                
        //validamos si el usuario esta en algun grupo que posee el tema asociado mediante un modulo
        //obtenemos modulo
        $module = $this->modules_model->getByid($moduleObject->modules_id);
        if(empty($module[0])){
            $error = new stdClass();
            $error->title = "Modulo [$moduleObject->modules_id] no existe";
            $error->message = "Caso mal configurado con modulo y grupo.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/404",$data);
            return;
        }

        $module = $module[0];
        $conditions = new stdClass();
        $conditions->users_id = $uid;
        $conditions->groups_id = $module->groups_id;
        $rolgroup = $this->role_group_model->get($conditions);

        //tiene el usuario asociado el objeto? 403
        if(empty($rolgroup[0])){
            $error = new stdClass();
            $error->title = "Usuario [$userEmail] sin permisos de acceso al Caso $object->name";
            $error->message = "El caso no esta relacionado con los temas inscritos al usuario.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //el objeto esta DISABLED?
        if($object->status == $cfg->object_disabled){
            $error = new stdClass();
            $error->title = "El Caso se encuentra deshabilitado por su creador";
            $error->message = "";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }
        //esta en desarrollo? 403
        if($object->status == $cfg->object_develop){
            $error = new stdClass();
            $error->title = "El Caso se encuentra en desarrollo";
            $error->message = "El creador del Caso se encuentra efectuando cambios.";
            $data['error'] = $error;
            $data['breadcumb'] = "Tema";
            $this->layout->view("/errors/403",$data);
            return;
        }

        //tiene aprobados los pre-requisitos?
        if($cfg->validate_requisites){
            $res = $this->objects_objects_model->getObjectsById($object->id);
            $invalidObjects = array();
            if(count($res['items'])>0){
                $requisites = $res['items'];
                $objectsIds = array();
                foreach($requisites as $requisite){
                    //obtenemos historial de ejecucion de cada requisito y vemos si esta ok
                    $query = new stdClass();
                    $query->users_id = $uid;
                    $query->objects = $requisite->id;
                    $query->objectversion = $requisite->version;
                    $query->type_objects_id = $cfg->type_object_theme;
                    $query->direction = "DESC";
                    $query->single = true;
                    $execObject = $this->users_exec_model->getExecutedObjects($query);
                    if($execObject!=null){
                        //si aun se esta ejecutando
                        if($execObject->status == $cfg->object_user_exec){
                            $requisite->status = "En ejecución";
                            $invalidObjects[] = $requisite;
                        }    
                        else{
                            //si solo se finalizo pero no se ha rendido la pruebva presencial para aprobarlo
                            if($execObject->status == $cfg->object_user_finished){
                                $requisite->status = "Finalizado pero sin aprobación";
                                $invalidObjects[] = $requisite;
                            }   
                        }
                    }
                    else{
                        //aun no se comienza
                        $requisite->status = "Sin iniciar";
                        $invalidObjects[] = $requisite;
                    }
                }
                //existen objetos sin aprobar
                if(count($invalidObjects)>0){
                    $message = "";
                    foreach($invalidObjects as $invalid){
                        $message .= "<strong>Tema</strong>: $invalid->name, <strong>version</strong>: $invalid->version, <strong>estado</strong>: $invalid->status<br>";    
                    }
                    $error = new stdClass();
                    $error->title = "El Caso Clinico no puede ejecutarse si posee requisitos pendientes";
                    $error->message = $message;

                    $data['error'] = $error;
                    $data['breadcumb'] = "Tema";
                    $this->layout->view("/errors/403",$data);
                    return;
                }
            }
        }
        

        $data['object'] = $object;
        $data['breadcumb'] = "Tema";
        $data['cfg'] = $cfg;
        $this->layout->view("/object/clinicalcase_exec",$data);
    }

    public function changeStatus(){
        $errors = array();
        $success = false;

        $this->load->library('utils');
        $cfg = $this->utils->getConfig();

        $this->load->model("users_exec_model");
        $this->load->model("modules_model");
        $this->load->model("modules_objects_model");
        $this->load->model("role_group_model");

        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');
        $object_id = $this->input->post('id');
        $status = $this->input->post('status');

        $object = $this->_modelInstance->getFull($object_id);
        //objeto existe
        if($object==null){
            $res = array(
                "success" => false,
                "message" => "Objeto $object_id no existe"
            );
            $this->layout->printLike(json_encode($res), "json");
            return;
        }

        //si se desea publicar objeto validamos contenido
        if($status == $cfg->object_publish){
            $object->version = $object->version+1;
            if($object->type_objects_id == $cfg->type_object_theme){
                //posee prueba?
                if(empty($object->test)){
                    $errors[] = "El Tema debe poseer una Prueba configurada";
                }
                else{
                    if(empty($object->test->questions)){
                        $errors[] = "La Prueba debe poseer Preguntas configuradas";       
                    }
                }
                //posee ppt?
                if(empty($object->presentation)){
                    $errors[] = "El Tema debe poseer una Presentación configurada";
                }
                else{
                    if(empty($object->presentation->slides)){
                        $errors[] = "La Presentación debe poseer Diapositivas configuradas";       
                    }
                }
                //posee objetos relacionados, notas de derivacion, imagenes, archivos etc?
                if(empty($object->relatedObjects)){
                    $errors[] = "El Tema debe poseer Archivos y/o Recursos asociados. Ejemplo: Notas de Derivación, Imágenes de Apoyo, Artículos PDF, etc.";
                }
            }
            else{
                if($object->type_objects_id == $cfg->type_object_theme){
                    //posee prueba?
                    if(empty($object->test)){
                        $errors[] = "El Caso debe poseer una Prueba configurada";
                    }
                    else{
                        if(empty($object->test->questions)){
                            $errors[] = "La Prueba debe poseer Preguntas configuradas";       
                        }
                    }
                }
            }
        }

        if(empty($errors)){
            $data = array(
                "id" => array(
                    'id'=>$object->id
                ),
                "data" => array(
                    'umodified'=>$userEmail,
                    "dmodified"=>date('Y-m-d H:i:s'),
                    "version"=>$object->version,
                    'status'=>$status
                )
            );
            
            if ($this->_modelInstance->save($data, true)) {
                $success = true;
            } else {
                $mensaje = "El objeto no pudo ser actualizado en su estado. Verifique los siguientes errores.";
                $errors = array("Error" => $this->_modelInstance->getError());
            }
        }
        $res = array(
            "success" => $success,
            "errors"=>$errors,
            "data"=>$object
        );
        $this->layout->printLike(json_encode($res), "json");
    }

    public function shedule(){
        $cfg = (object)$this->config->item('defaultCfg');
        $data['cfg'] = $cfg;
        $this->layout->view("/object/schedule", $data);
    }
    public function loadReport(){
        $cfg = (object)$this->config->item('defaultCfg');

        $this->load->model("modules_model");
        $this->load->model("objects_model");
        $this->load->model("objects_objects_model");
        $this->load->model("modules_objects_model");
        $this->load->model("users_exec_model");
        $this->load->model("users_model");
        $this->load->model("groups_model");
        
        $options = new stdClass();

        $groups_id = $this->session->userdata('groups_id');
        $uid = $this->session->userdata('id_usuario');
        $userEmail = $this->session->userdata('uid');

        $options->objects_id = $this->input->get('objects_id');
        
        $options->objects_start = $this->input->get('objects_start');
        $options->objects_end = $this->input->get('objects_end');

        $options->groups_id = $this->input->get('groups_id');
        $options->users_id = $this->input->get('users_id');
        
        $options->hit_start = $this->input->get('hit_start');
        $options->hit_end = $this->input->get('hit_end');
        $options->hit_status = $this->input->get('hit_status');
        $options->hit_objectsversion = $this->input->get('hit_objectsversion');
        
        $data = $this->users_exec_model->getReport1($options);
        $items = array();
        foreach ($data as $item) {
            $item->config = str_replace("&quot;", '"', $item->config);
            $item->config = json_decode($item->config);
            if(!empty($options->objects_start) && 
                strtotime($item->config->start) < strtotime($options->objects_start) ){
                continue;
            }
            if(!empty($options->objects_end) && 
                strtotime($item->config->end) > strtotime($options->objects_end)){
                continue;
            }
            $items[] = $item;
        }


        $res = array(
            "success" => true,
            "results" => count($items),
            "rows" => $items
        );
        $this->layout->printLike(json_encode($res), "json");
    }
}

